<?php

namespace app\widgets;


use app\models\Post;
use app\utils\ArrayUtils;
use yii\base\Widget;
use yii\helpers\Html;
use yii\helpers\Url;

class WebPageWidget extends Widget {

    public function run() {
        $menus = Post::find()
            ->where(['type' => Post::TYPE_PAGE])
            ->orderBy('sort asc, id desc')
            ->asArray()
            ->indexBy('id')
            ->all();
        $lists = ArrayUtils::arrayTree($menus, 'id', 'pid');
        $lists = array_slice($lists, 0, 3);

        $lines = [];
        foreach ($lists as $list) {
            $item = $this->renderItem($list);
            $lines[] = Html::tag('ul', $item);
        }
        return implode("\n", $lines);
    }

    protected function renderItem($item) {
        $lines = [];
        $lines[] = Html::tag('div', $item['title'], ['class' => 'fn-title']);
        if (isset($item['child'])) {
            foreach ($item['child'] as $k => $child) {
                if ($k > 3) {
                    break;
                }
                $url = Url::to(['page/view', 'id' => $child['id']]);
                $lines[] = "<li><a href=\"{$url}\">{$child['title']}</a></li>";
            }
        }
        return implode("\n", $lines);
    }

}